﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Model
{
    [ObjectEvent]
    public class BattleEventWatcherComponentEvent : ObjectEvent<BattleEventWatcherComponent>, IAwake
    {
        public void Awake()
        {
            Get().Awake();
        }
    }
    public class BattleEventWatcherComponent : Component
    {
        public static BattleEventWatcherComponent Single;
        Dictionary<BattleEventType, List<BattleEventComponent>> dic=new Dictionary<BattleEventType, List<BattleEventComponent>>();

        public void Awake()
        {
            Single = this;
        }

        public void AddEvent(BattleEventType eventType, BattleEventComponent battleEventComponent)
        {
            List<BattleEventComponent> list = null;
            dic.TryGetValue(eventType, out list);
            if (list == null)
            {
                list = new List<BattleEventComponent>();
                dic.Add(eventType, list);
            }
            for (int i = 0; i <list.Count; i++)
            {
                if (list[i].SortIndex >= battleEventComponent.SortIndex)
                {
                    //Log.Debug($"type:{eventType} ,{battleEventComponent.GetType().Name}插入{i}+{list[i].SortIndex}+{ battleEventComponent.SortIndex}");
                    list.Insert(i, battleEventComponent);
                    return;
                }
            }
            //Log.Debug($"type:{eventType}没有东西,{battleEventComponent.GetType().Name}");
            list.Insert(0, battleEventComponent);
        }
        public void RemoveEvent(BattleEventType eventType, BattleEventComponent battleEventComponent)
        {
            dic[eventType].Remove(battleEventComponent);
        }

        public async Task RunEvent(BattleEventType eventType,FightModel fightModel, params object[] param)
        {
            List<BattleEventComponent> list = null;
            dic.TryGetValue(eventType, out list);
            if (list == null) return;
            for (int i = 0; i < list.Count; i++)
            {
                if (!fightModel.TrapUseAble && list[i].IfTrap)
                    continue;
                await list[i].RunEvent(eventType, fightModel, param);
            }
        }
    }
}
